package net.adst.aunthenticate;

import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attributes;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import javax.naming.ldap.InitialLdapContext;
import javax.naming.ldap.LdapContext;
import javax.swing.*;
import java.util.Hashtable;

/**
 * Created with IntelliJ IDEA.
 * User: alekseipot
 * Date: 01.11.12
 * Time: 6:42
 * To change this template use File | Settings | File Templates.
 */
public class Authenticator {
//    private static final org.apache.log4j.Logger log = org.apache.log4j.Logger.getLogger(Authenticator.class);

    public static String getSetting(String key) {
//        if (StoredUserSettingsManager.getSetting(key) == null) {
//            return ResourceManager.getSettingString(key);
//        } else {
//            return StoredUserSettingsManager.getSetting(key);
//        }
        return "tra-ta-ta-ta";
    }

    public static StoredUser authenticate(String user, String pass) {
//        ResourceBundle resourceBundle = ResourceBundle.getBundle("resources.settings");

        Hashtable<String, String> env = new Hashtable<String, String>();
        env.put(Context.INITIAL_CONTEXT_FACTORY, getSetting("ldap.initialContextFactory"));
        env.put(Context.PROVIDER_URL, getSetting("ldap.host"));
        env.put(Context.SECURITY_AUTHENTICATION, getSetting("ldap.securityAuthentication"));
        env.put(Context.SECURITY_PROTOCOL, getSetting("ldap.securityProtocol"));
//        env.put(Context.SECURITY_PRINCIPAL, SmartLogin.filter(user, getSetting("smartLogin.domain")));
        env.put(Context.SECURITY_CREDENTIALS, pass);
//        LdapContext ctxGC = null;
        try {
            LdapContext ctxGC = new InitialLdapContext(env, null);
            String returnedAtts[] = {"sn", "givenName", "mail"};
            String userId = user.substring(user.indexOf("\\") + 1, user.length());
            String searchFilter = "(&(objectClass=user)(sAMAccountName=" + userId + "))";
            SearchControls searchCtls = new SearchControls();
            searchCtls.setReturningAttributes(returnedAtts);
            searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
            NamingEnumeration<SearchResult> answer = ctxGC.search(getSetting("ldap.searchBase"), searchFilter, searchCtls);
            while (answer.hasMoreElements()) {
                SearchResult sr = answer.next();
                Attributes attrs = sr.getAttributes();
                if (attrs != null) {
                    String firstName = attrs.get("givenName").toString();
                    String mail = attrs.get("mail") != null ? attrs.get("mail").toString() : "";
                    String surName = attrs.get("sn") != null ? attrs.get("sn").toString() : "";
                    return new StoredUser(firstName.substring(firstName.indexOf(" ") + 1, firstName.length()), surName.substring(surName.indexOf(" ") + 1, surName.length()), mail.substring(mail.indexOf(" ") + 1, mail.length()));
                }
            }
            return null;
        } catch (NamingException ex) {
            ex.printStackTrace();
//            log.error("NamingException", ex);
//            if (DataManager.getObject(ResourceManager.getVariableName("ui.settingsPanel.connectionSettings.button")) != null) {
//                ((JButton) DataManager.getObject(ResourceManager.getVariableName("ui.settingsPanel.connectionSettings.button"))).setEnabled(true);
//            }
            return null;
        }
    }

}
